package com.ynr.voucher.service.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ynr.voucher.dao.IDictionaryDao;
import com.ynr.voucher.model.FaModel;
import com.ynr.voucher.model.InvoiceItemModel;
import com.ynr.voucher.service.IFAMatchService;

/**
 * 匹配出固定资产的类型
 */
@Service
public class FAMatchServiceImpl implements IFAMatchService {

	private static final Logger logger = LoggerFactory.getLogger(FAMatchServiceImpl.class);

	@Autowired
	private IDictionaryDao dictionaryDao;
	
	private static List<FaModel> faList = null;
	
	@Override
	public FaModel faMatchService(InvoiceItemModel item, Map<String, Object> companyMap, String fplx) {
		long companyId = (long)companyMap.get("id");
		int companyType= (int)companyMap.get("type");
		logger.debug("faMatchService param companyId : {}, companyType : {}", companyId, companyType);
		//公司自定义固定资产字典库
		List<Map<String, Object>> companyFaDictionary = dictionaryDao.getCompanyFaDic(companyId);
		//公共固定资产字典库
		List<Map<String, Object>> commonFaDictionary = dictionaryDao.getCommonFaDic();
		if(companyFaDictionary != null && companyFaDictionary.size() > 0) {
			for(Map<String, Object> companyFa : companyFaDictionary) {
				if(item.getName().contains((String)companyFa.get("content"))) {
					int faType = (int)companyFa.get("type");
					if(companyType == 1) {
						return isFa(item, faType, false);
					} else if(companyType == 2) {
						return isFa(item, faType, fplx.equals("01")?true:false);
					}
				}
			}
		}
		for(Map<String, Object> commonFa : commonFaDictionary) {
			if(item.getName().contains((String)commonFa.get("content"))) {
				int faType = (int)commonFa.get("type");
				if(companyType == 1) {
					return isFa(item, faType, false);
				} else if(companyType == 2) {
					return isFa(item, faType, fplx.equals("01")?true:false);
				}
			}
		}
		return null;
	}
	
	private FaModel isFa(InvoiceItemModel item, int faType, boolean isSpecial) {
		if(faList == null) {
			faList = dictionaryDao.getFaType();
		}
		for(FaModel fa : faList){
			if(fa.getType() == faType) {
				if((Double.valueOf(item.getTax_sum()) + (isSpecial?Double.valueOf(item.getTax_sum()):0)) >= fa.getAmount()) {
					return fa;				
					} 
				else return null;
			}
		}
		return null;
	}
	
}
